# -*- coding:utf-8 -*-

import requests
import logging
from threading import Thread
import allure
from utils.api_monitor import ApiLogger
from utils.path_management import *


class HttpRequester:
    def __init__(self, slow_api_logger=None, timeout=30):
        self.slow_api_logger = slow_api_logger or ApiLogger(slow_api_path())
        self.timeout = timeout  # 默认超时时间

    @allure.step("发送HTTP请求")
    def send_request(self, **request_data):
        return self._send_request(**request_data)

    def _send_request(self, **request_data):
        # 参数验证
        required_fields = ['method', 'url']
        if not all(field in request_data for field in required_fields):
            raise ValueError(f"请求缺少必传参数: {required_fields}")

        # 设置默认值
        request_data.setdefault('timeout', self.timeout)
        request_data.setdefault('params', {})
        request_data.setdefault('data', {})
        request_data.setdefault('json', None)
        request_data.setdefault('headers', {})

        try:
            # 发送HTTP请求
            with requests.Session() as session:
                res = session.request(**request_data)

            # 记录响应信息
            logging.info(f"2.发送HTTP请求, URL: {res.url}, 响应状态码: {res.status_code}, 响应文本: {res.text[:100]}...")

            # 计算响应时间（毫秒）
            response_time_ms = res.elapsed.total_seconds() * 1000

            # 异步写入慢接口数据
            self._log_slow_api_async(res, request_data, response_time_ms)

            # 尝试解析响应体为JSON
            try:
                data = res.json()
            except ValueError:
                data = res.text  # 如果不是JSON，则直接返回文本

            return {
                "status_code": res.status_code,
                "response_time": response_time_ms,
                "data": data
            }

        except requests.RequestException as e:
            logging.error(f"HTTP请求失败: {e}")
            return {"error": str(e)}
        except Exception as e:
            logging.error(f"发生未知错误: {e}")
            return {"error": "An unexpected error occurred"}

    def _log_slow_api_async(self, res, request_data, response_time_ms):
        """异步记录慢接口日志"""
        def log():
            self.slow_api_logger.log_request(
                res.url,
                res.request.method,
                request_data.get("params", {}),
                request_data.get("data", {}),
                request_data.get("json", {}),
                response_time_ms
            )
        Thread(target=log).start()

# 使用装饰器来简化调用
def http_request_wrapper(func):
    def wrapper(*args,**kwargs):
        data = func(*args,**kwargs)
        http_requester = HttpRequester()
        return http_requester.send_request(**data)
    return wrapper

# 示例使用
@http_request_wrapper
def example_http_request():
    # 这里可以传递任何requests.request支持的参数
    return {
        'method': 'GET',
        'url': 'https://api.example.com/data',
        'params': {'key1': 'value1'},
        'headers': {'User-Agent': 'Custom User Agent'}
    }

if __name__ == "__main__":
    response = example_http_request()
    print(response)